package com.liduanwei.update.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Wei on 17/10/3.
 */
public class DownloadUtil {
    private static AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis());

    public static void downloadZipFileAndDecompress(String zipFileUrl, String fileName, DecompressCallback decompressCallback) throws IOException {

        File destFile = new File("./" + fileName + "_tmpZipFile_" /*+ atomicLong.getAndIncrement()*/);
        PrintUtil.Companion.print("####, downloading...: " + destFile.getAbsolutePath());
        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        HttpUtil.download(zipFileUrl, new HttpUtil.DownloadCallback() {
            public void onProgress(byte[] bytes, int len) {
                try {
                    fileOutputStream.write(bytes, 0, len);
                } catch (IOException e) {
                    e.printStackTrace();
                    decompressCallback.onComplete(false);
                }
            }

            public void onComplete(boolean isSuccessfully) {
                try {
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    String decompressDestDirectory = OSUtil.Companion.isLinux() ? "/" : "";
                    FileUtil.decompress(destFile.getAbsolutePath(), decompressDestDirectory);
                    decompressCallback.onComplete(true);
                } catch (Exception e) {
                    e.printStackTrace();
                    decompressCallback.onComplete(false);
                }
            }
        });
    }

    static public interface DecompressCallback {
        void onComplete(boolean isSuccessfully);
    }
}
